import Vue from 'vue';
import Router from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {AUTHORIZATION} from '../store/mutation-types';
import {constantRouterMap} from './router.config';
import Config from '@/config/config';
import store from '../store';

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err);
};
Vue.use(Router);
let router = new Router({
    scrollBehavior: () => ({
        y: 0
    }),
    routes: constantRouterMap
});

NProgress.configure({
    showSpinner: false
});
router.beforeEach((to, from, next) => {
    NProgress.start();
    let authorization = Vue.ls.get(AUTHORIZATION);
    if (to.name !== 'login' && authorization && authorization['token']) {
        if (!store.state.context.authorization.token) {
            store.dispatch('setAuthorization',authorization);
            next({
                ...to,
                replace: true
            });
        } else {
            next();
        }
        NProgress.done();
    } else {
        if (Config.router.whiteList.includes(to.name)) {
            next();
        } else {
            next({ name: 'login', query: { redirect: to.fullPath } });
            NProgress.done();
        }
    }
});
router.afterEach(() => {
    NProgress.done();
});
router.onError((error) => {
    console.log('router：error');
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    const targetPath = router.history.pending.fullPath;
    if (isChunkLoadFailed) {
        router.replace(targetPath);
    }
});
export default router;
